from datetime import datetime
import json

import tornado.ioloop
import tornado.web
from openai import OpenAI

from Translate import translate_object_hook
from auth import all_keys
openaiClient = OpenAI(
    api_key="sk-34",
    base_url="https://api.atpgroup.work/v1"
)

class MainHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")  # 允许所有来源访问，也可以指定特定的来源
        self.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
        self.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")  # 可接受的请求方法

    def get(self):
        self.write("Hello, Tornado!")

    def post(self):
        self.write("Hello, Tornado!")

    def options(self):
        # 响应 OPTIONS 请求
        self.set_status(204)
        self.finish()


class TranslateHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")  # 允许所有来源访问，也可以指定特定的来源
        self.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
        self.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")  # 可接受的请求方法

    async def post(self):
        self.set_header('Content-Type', 'text/event-stream')
        self.set_header('Cache-Control', 'no-cache')
        self.set_header('Connection', 'keep-alive')
        try:
            authorization_header = self.request.headers.get("Authorization")
            if authorization_header not in all_keys:
                self.send_error(401)
            json_str = self.request.body.decode('utf-8')
            translate = json.loads(json_str, object_hook=translate_object_hook)
            response = openaiClient.chat.completions.create(
                model="gpt-3.5-turbo-1106",
                messages=[
                    {"role": "user", "content": translate.getRequestPrompt()}
                ],
                stream=True  # 是否开启流式输出
            )
            # 按流读取数据
            for message in response:
                print(type(message.choices[0].delta.content))
                if type(message.choices[0].delta.content) is str:
                    self.write(message.choices[0].delta.content)
                await self.flush()

        except Exception as e:
            print(e)
            self.write("error")
        await self.flush()
        await self.finish()
        print("closed")

    def options(self):
        # 响应 OPTIONS 请求
        self.set_header('Content-Type', 'text/event-stream')
        self.set_header('Cache-Control', 'no-cache')
        self.set_header('Connection', 'keep-alive')
        self.set_status(204)
        self.finish()


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/translate", TranslateHandler),
    ])
